package com.xoa.service.BBS.Impl;

import com.xoa.dao.BBS.BbsBoardMapper;
import com.xoa.dao.BBS.BbsCommentMapper;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.users.UserPrivMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.BBS.BbsBoard;
import com.xoa.model.BBS.BbsBoardWithBLOBs;
import com.xoa.model.common.SysCode;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.users.Users;
import com.xoa.service.BBS.BbsBoardService;
import com.xoa.service.ThreadSerivice.ThreadService;
import com.xoa.service.sms.SmsService;
import com.xoa.service.smsDelivery.Sms2PrivService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class BbsBoardServiceImpl implements BbsBoardService{

    @Autowired
    BbsBoardMapper bbsBoardMapper;

    @Autowired
    DepartmentMapper departmentMapper;

    @Autowired
    UsersMapper usersMapper;

    @Autowired
    UserPrivMapper userPrivMapper;

    @Autowired
    BbsCommentMapper bbsCommentMapper;

    @Resource
    private SmsService smsService;
    @Resource
    ThreadService threadService;
    @Resource
    ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Resource
    private SysCodeMapper sysCodeMapper;
    @Resource
    Sms2PrivService sms2PrivService;

    /**
     * 新增讨论区
     * @param record
     * @param request
     * @param ifAddAffairs：为判断是否需要事务提醒的字段，当为1时为需要事务提醒
     * @param ifSms2Priv：判断是否需要短信提醒的字段，为1 时是需要短信提醒
     * @return
     */
    @Override
    public ToJson<BbsBoard> insertSelective(BbsBoardWithBLOBs record,HttpServletRequest request,Integer ifAddAffairs,Integer ifSms2Priv) {
        ToJson toJson = new ToJson(1,"false");
        try {
            record.setParentId(0);

            if (StringUtils.checkNull(record.getDeptId())){
                record.setDeptId("");
            }
            if (StringUtils.checkNull(record.getPrivId())){
                record.setPrivId("");
            }
            if (StringUtils.checkNull(record.getUserId())){
                record.setUserId("");
            }

            int count = bbsBoardMapper.insertSelective(record);
            if(count > 0){
                toJson.setMsg("true");
                toJson.setFlag(0);
            }

        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    /**
     * 查询讨论区内容
     * @return
     * @param request
     * @param purview
     * @param page
     * @param limit
     */
    @Override
    public ToJson<BbsBoard> selectAll(HttpServletRequest request, boolean purview, Integer page, Integer limit) {
        ToJson toJson = new ToJson(1,"false");
        Map map=new HashMap();
        //分页设置
        try {
            PageParams pageParams=new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(limit);
            pageParams.setUseFlag(true);
            map.put("pageParams",pageParams);
        }catch (Exception e){
            e.printStackTrace();
        }
        try{
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
            //是否开启权限
            if(purview){
                map.put("deptId",users.getDeptId());
                map.put("privId",users.getUserPriv());
                map.put("userId",users.getUserId());
                map.put("boardHoster",users.getUserId());
            }

            Map map1=new HashMap();
            List<BbsBoardWithBLOBs> list1 = bbsBoardMapper.selectAll(map);
            for (BbsBoardWithBLOBs board:list1) {
                //部门
                if (!StringUtils.checkNull(board.getDeptId())){
                    if (board.getDeptId().equals("ALL_DEPT")){
                        board.setDeptName("全体部门");
                    }else{
                        map1.put("ids",board.getDeptId().split(","));
                        map1.put("tableName","department");
                        map1.put("field","DEPT_ID");
                        map1.put("concat","DEPT_NAME");
                        map1.put("order","DEPT_ID");
                        String deptName = bbsBoardMapper.findNames(map1);
                        board.setDeptName(deptName);
                    }
                }
                //角色
                if (!StringUtils.checkNull(board.getPrivId())){
                    map1.put("ids",board.getPrivId().split(","));
                    map1.put("tableName","user_priv");
                    map1.put("field","USER_PRIV");
                    map1.put("concat","PRIV_NAME");
                    map1.put("order","USER_PRIV");
                    String PrivName = bbsBoardMapper.findNames(map1);
                    board.setPrivName(PrivName);
                }
                //人员
                if (!StringUtils.checkNull(board.getUserId())){
                    map1.put("ids",board.getUserId().split(","));
                    map1.put("tableName","user");
                    map1.put("field","USER_ID");
                    map1.put("concat","USER_NAME");
                    map1.put("order","UID");

                    String userName = bbsBoardMapper.findNames(map1);
                    board.setUserName(userName);
                }
                //版主
                if (!StringUtils.checkNull(board.getBoardHoster())){
                    map1.put("ids",board.getBoardHoster().split(","));
                    map1.put("tableName","user");
                    map1.put("field","USER_ID");
                    map1.put("concat","USER_NAME");
                    map1.put("order","UID");
                    String BoardHosterName = bbsBoardMapper.findNames(map1);
                    board.setBoardHosterName(BoardHosterName);
                }

                //主题
                map.clear();
                map.put("boardId",board.getBoardId());
                map.put("parent","0");
                map.put("isparent","=");
                board.setThemeNums(bbsBoardMapper.findCountComment(map));

                //帖数
                map.put("boardId",board.getBoardId());
                map.put("parent","0");
                map.put("isparent","<>");
                board.setPostNums(bbsBoardMapper.findCountComment(map));

                //最后发表
                board.setLastRelease(bbsCommentMapper.findLastRelease(map));

            }
            if(list1.size()>0){
                toJson.setFlag(0);
                toJson.setMsg("true");
                toJson.setObj(list1);
            }
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }


    /**
     * 修改讨论区设置
     * @param record
     * @return
     */
    @Override
    public ToJson<BbsBoard> updateByPrimaryKeyWithBLOBs(BbsBoardWithBLOBs record) {
        ToJson toJson = new ToJson(1,"false");
        try {
            int count = bbsBoardMapper.updateByPrimaryKeySelective(record);
            if(count > 0){
                toJson.setFlag(0);
                toJson.setMsg("ok");
            }
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    /**
     * 删除信息
     * @param boardId
     * @return
     */
    @Override
    public ToJson<BbsBoard> deleteByPrimaryKey(Integer boardId) {
        ToJson toJson = new ToJson(1,"false");
        try{
            int i = bbsBoardMapper.deleteByPrimaryKey(boardId);
            if(i > 0){
                int j = bbsCommentMapper.deleteByBoardId(boardId);
                toJson.setFlag(0);
                toJson.setMsg("ok");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return toJson;
    }

    /**
     * 查询单个的讨论区
     * @param boardId
     * @return
     */
    @Override
    public ToJson<BbsBoard> selectByPrimaryKey(Integer boardId) {
        ToJson toJson = new ToJson();
        try{
            BbsBoardWithBLOBs bbsBoardWithBLOBs = bbsBoardMapper.selectByPrimaryKey(boardId);
            if(bbsBoardWithBLOBs.getDeptId() != null && !bbsBoardWithBLOBs.getDeptId().equals("")){
                StringBuffer sb = new StringBuffer();
                if(bbsBoardWithBLOBs.getDeptId().equals("ALL_DEPT")){
                    bbsBoardWithBLOBs.setDeptName("全部部门");
                }else{
                    String strArr[] = bbsBoardWithBLOBs.getDeptId().split(",");
                    for(int i = 0;i < strArr.length;i++){
                        int deptId = Integer.parseInt(strArr[i]);
                        String deptName= departmentMapper.getDeptNameById(deptId);
                        sb.append(deptName+ ",");
                    }
                    bbsBoardWithBLOBs.setDeptName(sb.toString());
                }
            }
            //对角色Id进行转换
            if(bbsBoardWithBLOBs.getPrivId() != null && !bbsBoardWithBLOBs.getPrivId().equals("")){
                StringBuffer sb = new StringBuffer();

                    String strArr[] = bbsBoardWithBLOBs.getPrivId().split(",");
                    for(int i = 0;i < strArr.length;i++){
                        int privId = Integer.parseInt(strArr[i]);
                        String privName= userPrivMapper.getPrivNameByPrivId(privId);
                        sb.append(privName+ ",");
                    }
                    bbsBoardWithBLOBs.setPrivName(sb.toString());

            }
            //对角色Id进行转换
            if(bbsBoardWithBLOBs.getUserId() != null && !bbsBoardWithBLOBs.getUserId().equals("")){
                StringBuffer sb = new StringBuffer();

                    String strArr[] = bbsBoardWithBLOBs.getUserId().split(",");
                    for(int i = 0;i < strArr.length;i++){
                        String userName= usersMapper.getUsernameByUserId(strArr[i]);
                        sb.append(userName+ ",");
                    }
                    bbsBoardWithBLOBs.setUserName(sb.toString());

            }

            //版主
            if(bbsBoardWithBLOBs.getBoardHoster() != null && !bbsBoardWithBLOBs.getBoardHoster().equals("")){
                StringBuffer sb = new StringBuffer();
                String strArr[] = bbsBoardWithBLOBs.getBoardHoster().split(",");
                for(int i = 0;i < strArr.length;i++){
                    String userName= usersMapper.getUsernameByUserId(strArr[i]);
                    sb.append(userName+ ",");
                }
                bbsBoardWithBLOBs.setBoardHosterName(sb.toString());
            }


            if(bbsBoardWithBLOBs != null){
                toJson.setFlag(0);
                toJson.setMsg("ok");
                toJson.setObject(bbsBoardWithBLOBs);
            }else{
                toJson.setFlag(1);
                toJson.setMsg("err");
            }
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;

    }

    /**
     * 讨论区列表显示
     * @param record
     * @return
     */
    @Override
    public ToJson<BbsBoard> selectCommentBoard(HttpServletRequest request,BbsBoardWithBLOBs record) {
        ToJson toJson = new ToJson(1,"err");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        String  deptId = users.getDeptId().toString();
        String privId =  users.getUserPriv().toString();
        String userId = users.getUserId();
        record.setDeptId(deptId);
        record.setPrivId(privId);
        record.setUserId(userId);
        record.setBoardHoster(userId);
        try{
                List<BbsBoardWithBLOBs> list = bbsBoardMapper.selectCommentBoard(record);
                for(BbsBoardWithBLOBs bbsBoardWithBLOBs:list ) {
                //版主
                if(bbsBoardWithBLOBs.getBoardHoster() != null && !bbsBoardWithBLOBs.getBoardHoster().equals("")){
                    StringBuffer sb = new StringBuffer();
                    String strArr[] = bbsBoardWithBLOBs.getBoardHoster().split(",");
                    for(int i = 0;i < strArr.length;i++){
                        String userName= usersMapper.getUsernameByUserId(strArr[i]);
                        sb.append(userName+ ",");
                    }
                    bbsBoardWithBLOBs.setBoardHosterName(sb.toString());
                }
               /* //最后发布人及时间
                int i = bbsBoardWithBLOBs.getBoardId();
                BbsCommentWithBLOBs bbsCommentWithBLOBs = bbsCommentMapper.selLastPublicPerson(i);
                if(bbsCommentWithBLOBs != null){
                    int temp = bbsCommentWithBLOBs.getAuthorNameTmep();
                    switch (temp){
                        case 1: bbsBoardWithBLOBs.setLastPublishName(bbsCommentWithBLOBs.getAuthorName());
                            break;
                        case 2:bbsBoardWithBLOBs.setLastPublishName(bbsCommentWithBLOBs.getNickName());
                            break;
                        default:bbsBoardWithBLOBs.setLastPublishName("");
                    }

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    String date = sdf.format(bbsCommentWithBLOBs.getOldSubmitTime());
                    bbsBoardWithBLOBs.setLastPublishTime(date);
                }else{
                    bbsBoardWithBLOBs.setLastPublishName("");
                    bbsBoardWithBLOBs.setLastPublishTime("");
                }*/

            }
            if(list.size() >= 0){
                toJson.setFlag(0);
                toJson.setMsg("ok");
                toJson.setObj(list);

            }
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }


    /**
     * 给讨论区设置添加提醒事务
     *
     * @param
     */
    @Async
    public void addAffairs(HttpServletRequest request,BbsBoardWithBLOBs bbsBoard, final Integer boardId, final String todoId) {
        final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        final String userName = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users()).getUserName();
        final BbsBoardWithBLOBs bbsBoardf = bbsBoard;
        this.threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ContextHolder.setConsumerType("xoa" + sqlType);
                SmsBody smsBody = new SmsBody();
                smsBody.setFromId(bbsBoardf.getBoardHoster());
                smsBody.setContent("讨论区！主题：" + bbsBoardf.getBoardName());
                Date date = new Date();
                long dateLong = date.getTime()/1000;
                String strDate = String.valueOf(dateLong);
                Integer dateInt = Integer.valueOf(strDate.trim());
                smsBody.setSendTime(dateInt);
                SysCode sysCode = new SysCode();
                sysCode.setCodeName("内部讨论区");
                sysCode.setParentNo("SMS_REMIND");
                if (sysCodeMapper.getCodeNoByNameAndParentNo(sysCode) != null) {
                    smsBody.setSmsType(sysCodeMapper.getCodeNoByNameAndParentNo(sysCode).getCodeNo());
                }
                smsBody.setRemindUrl("system/bbs/getDetail?boardId=" + boardId);
                String title = userName + "：新建讨论区！";
                String context = "主题:" + bbsBoardf.getBoardName();
                smsService.saveSms(smsBody, todoId, "1", "1", title, context, sqlType);
            }
        });

    }


}
